<?php
namespace app\api\controller;

use app\api\model\Orders;


use app\api\model\ModeOrders;
use app\api\model\User;
use app\hooks\ModeOneHook;
use app\hooks\ModeThreeHook;
use app\hooks\ModeTwoHook;
use app\hooks\UserHook;
use think\Request;

class Payments extends Base
{
    // 是否自动实例化当前模型
    protected $autoNewModel = false;
    // 是否开启自动验证
    protected $autoValidateCheck = false;

    public function information(Request $request){
        $params = request()->param();
        $orderSn = $params['union_order_sn'];
        //查询订单信息
        $order_info = Orders::where('order_sn', $orderSn)->findOrEmpty()->toArray();
        //整理数据
        $data = [
            'order_sn'=>$orderSn,
            'pay_amount' => (float)$order_info['total_amount'],//(int)bcmul((float)$order_info['total_fee'], 100, 0),
            'goods_amount' => (float)$order_info['total_original_amount'],//(int)bcmul((float)$order_info['goods_original_amount'], 100, 0),
            'express_amount' => (float)$order_info['dispatch_amount'],//(int)bcmul((float)$order_info['dispatch_amount'], 100, 0),
            'discount_amount' => (float)$order_info['discount_amount'],//(int)bcmul((float)$order_info['discount_fee'], 100, 0),
            'payments'=>[],
        ];
        //判断当前设备类型
        switch (data_get($params, 'platform', 'h5')) {
            case 'plus':
                //设置app支付通道
                $data['payments'] = [
//                    ['alias' => 'wechat.app', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
//                    ['alias' => 'alipay.app', 'name' => '支付宝支付', 'tip' => '国民支付，方便快捷', 'icon' => get_oss_url('/static/alipay.png')],
//
                ];
                break;
            case 'mp':
                //设置小程序支付通道
                $data['payments'] = [
//                    ['alias' => 'wechat.mini', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
                ];
                break;
            case 'h5':
                //判断是否为微信支付
                if (strpos($request->header('user-agent'), 'MicroMessenger') !== false) {
                    //设置默认支付通道
                    $data['payments'] = [
//                        ['alias' => 'wechat.mp', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
                    ];
                } else {
                    //设置默认支付通道
                    $data['payments'] = [
//                        ['alias' => 'wechat.h5', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
//                        ['alias' => 'alipay.h5', 'name' => '支付宝支付', 'tip' => '国民支付，方便快捷', 'icon' => get_oss_url('/static/alipay.png')],
//
                    ];
                }
                break;
        }

        //TODO： 根据商品类型判断是否追加余额、积分、绿色积分的支付方式
        $data['payments'][] = ['alias' => 'score', 'name' => '我的积分支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_local_url('/static/system/cashier/score.png')];


        //响应数据
        return showSuccess($data);
    }

    public function method()
    {
        $params = request()->param();
        $userId = request()->UserModel->id;
        $orderSn = $params['order_sn'];
        $alias = $params['alias'];
        $orders = Orders::where('order_sn', $orderSn)
            ->where('user_id', $userId)->find();
        $totalAmount = $orders['total_amount'];
        $type = 'shop_pay';
        if($orders['status'] == 'payed'){
            return showError('请勿重复支付');
        }
        switch ($alias){
            case 'score':{
                $currentAlias = User::where('id', $userId)->value($alias);
                if($currentAlias < $totalAmount){
                    return showError('可用额度不足');
                }
                $isDone = Orders::afterShopping($orders['id'], $userId, $alias, $type);
                if($isDone === true){
                    return showSuccess([], '支付成功');
                }else{
                    return showError('支付失败');
                }
            }
                break;

        }
        return true;
    }

    public function modeInformation(){
        $params = request()->param();
        $orderSn = $params['union_order_sn'];
        //查询订单信息
        $order_info = ModeOrders::where('order_sn', $orderSn)->findOrEmpty()->toArray();
        //整理数据
        $data = [
            'order_sn'=>$orderSn,
            'pay_amount' => (int)$order_info['pay_amount'],//(int)bcmul((float)$order_info['pay_amount'], 100, 0),
            'goods_amount' =>(int)$order_info['pay_amount'],//(int)bcmul((float)$order_info['pay_amount'], 100, 0),
            'express_amount' => 0,//(int)bcmul((float)$order_info['dispatch_amount'], 100, 0),
            'discount_amount' => 0,//(int)bcmul((float)$order_info['discount_fee'], 100, 0),
            'payments'=>[],
        ];
        //判断当前设备类型
        switch (data_get($params, 'platform', 'h5')) {
            case 'plus':
                //设置app支付通道
                $data['payments'] = [
//                    ['alias' => 'wechat.app', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
//                    ['alias' => 'alipay.app', 'name' => '支付宝支付', 'tip' => '国民支付，方便快捷', 'icon' => get_oss_url('/static/alipay.png')],
                ];
                break;
            case 'mp':
                //设置小程序支付通道
                $data['payments'] = [
//                    ['alias' => 'wechat.mini', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
                ];
                break;
            case 'h5':
                //判断是否为微信支付
                if (strpos(request()->header('user-agent'), 'MicroMessenger') !== false) {
                    //设置默认支付通道
                    $data['payments'] = [
//                        ['alias' => 'wechat.mp', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
                    ];
                } else {
                    //设置默认支付通道
                    $data['payments'] = [
//                        ['alias' => 'wechat.h5', 'name' => '微信支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')],
//                        ['alias' => 'alipay.h5', 'name' => '支付宝支付', 'tip' => '国民支付，方便快捷', 'icon' => get_oss_url('/static/alipay.png')],
                    ];
                }
                break;
        }

        //TODO： 根据商品类型判断是否追加余额、积分、绿色积分的支付方式
        $data['payments'][] = ['alias' => 'balance', 'name' => '我的积分支付', 'tip' => '亿万用户的选择，更快更安全', 'icon' => get_oss_url('/static/weixin.png')];


        //响应数据
        return showSuccess($data);
    }

    public function modeMethod()
    {
        $params = request()->param();
        $userId = request()->UserModel->id;
        $orderSn = $params['order_sn'];
        $alias = $params['alias'];
        $modeOrders = ModeOrders::where('order_sn', $orderSn)
            ->where('user_id', $userId)->find();
        $totalAmount = $modeOrders['pay_amount'];
        $type = 'mode_pay';
        switch ($alias){
            case 'balance':{
                $currentAlias = User::where('id', $userId)->value($alias);
                if($currentAlias < $totalAmount){
                    return showError('可用额度不足');
                }
                //deduce($userId, $amount, $alias = 'money', $level1 = 0, $level2 = 0, $des = '')
                User::deduce($userId, $totalAmount, $alias, $type);

                ModeOrders::where('id', $modeOrders['id'])->update([
                    'status'=>'payed',
                    'pay_type'=>$alias,
                    'pay_real'=>$totalAmount,
                    'pay_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s'),
                ]);
                $this->afterPay($modeOrders);
                return showSuccess([], '支付成功');
            }
            break;

        }
        return true;
    }

    private function afterPay($modeOrders)
    {
        switch ((int)$modeOrders['type']) {
            case 1:
            case 2:

                User::where('id', $modeOrders['user_id'])->inc('mode_one_spending', $modeOrders['principal'])->update();

                ModeOneHook::paid_run($modeOrders['id']);

                break;

            case 3:

                User::where('id', $modeOrders['user_id'])->inc('welfare_points', (2000000 * $modeOrders['num']))->update();
                User::where('id', $modeOrders['user_id'])->inc('invest_count', $modeOrders['num'])->update();

                ModeTwoHook::paid_run($modeOrders['id']);


                break;
            case 4:


                User::where('id', $modeOrders['user_id'])->inc('mode_three_spending', $modeOrders['principal'])->update();
                ModeThreeHook::paid_run($modeOrders['id']);
                break;
        }
//        dd($modeOrders);
        return UserHook::run($modeOrders['user_id']);
    }


}